﻿using System;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using AutomatedDatabaseDR;

namespace SqlServerDRControlPanel
{
    public partial class CreateConfigDatabaseObjects : Form
    {
        private string m_ConfigServer;
        private string m_ConfigDatabase;

        public CreateConfigDatabaseObjects()
        {
            InitializeComponent();
        }

        void CreateConfigDatabaseObjects_Load(object sender, EventArgs e)
        {
            string[] ConfigItems = ConfigurationManager.AppSettings["ConfigDbConn"].Split('|');
            m_ConfigServer = ConfigItems[0];
            m_ConfigDatabase = ConfigItems[1];
            LblConfigDatabaseValue.Text = m_ConfigDatabase;
            
            LblServerValue.Text = m_ConfigServer;
            
            GetObjectStatus();
            // Button_CreateObjects.Enabled = true;
        }

        private void GetObjectStatus()
        {
            string retStr = "One or more objects do not exist.";
            ConfigItems ci = new ConfigItems();
            ci.ConfigServer = m_ConfigServer;
            ci.ConfigDB = m_ConfigDatabase;
            if (ci.ConfigObjectsExist())
            {
                retStr = "Database objects already exist";
                Lbl_ObjectStatus.Text = retStr;
                Lbl_ObjectStatus.ForeColor = Color.Green;
            }
            else
            {
                Lbl_ObjectStatus.ForeColor = Color.Red;
                Lbl_ObjectStatus.Text = retStr;
                Button_CreateObjects.Enabled = true;
            }
            

        }

        private void Button_CreateObjects_Click(object sender, EventArgs e)
        {
            ConfigItems ci = new ConfigItems();
            ci.ConfigServer = m_ConfigServer;
            ci.ConfigDB = m_ConfigDatabase;
            try
            {
                ci.CreateDatabaseObjects();
                GetObjectStatus();
            }
            catch (Exception exception)
            {
                LblOutput.Enabled = true;
                TbOutput.Enabled = true;
                TbOutput.Text = exception.InnerException.ToString();
            }
        }
    }
}
